package algorithm_demo.demo05;

/**
 * 最长公共子序列
 * 尝试模型的第三种：多样本位置全对应的尝试模型
 *
 * <a href="https://leetcode.cn/problems/longest-common-subsequence/">https://leetcode.cn/problems/longest-common-subsequence/</a>
 *
 * @author Api
 * @date 2023/3/21 23:18
 */
public class Code14_LongestCommonSubsequence {
    public int longestCommonSubsequence(String text1, String text2) {
        if (text1 == null || text1.length() == 0 || text2 == null || text2.length() == 0) {
            return 0;
        }
        char[] str1 = text1.toCharArray();
        char[] str2 = text2.toCharArray();
        return lcse(str1, str2);
    }

    /*
     * dp[i][j]的值来源四种可能性
     * 1. dp[i-1][j-1]
     * 2. dp[i-1][j]
     * 3. dp[i][j-1]
     * 4. if(str1[i] == str2[j]){
     *       dp[i-1][j-1]+1
     *    }
     * */
    public static int lcse(char[] str1, char[] str2) {
        int[][] dp = new int[str1.length][str2.length];
        dp[0][0] = str1[0] == str2[0] ? 1 : 0;
        //填写第0列的所有值
        for (int i = 1; i < str1.length; i++) {
            dp[i][0] = Math.max(dp[i - 1][0], str1[i] == str2[0] ? 1 : 0);
        }
        for (int j = 1; j < str2.length; j++) {
            dp[0][j] = Math.max(dp[0][j - 1], str1[0] == str2[j] ? 1 : 0);
        }
        for (int i = 1; i < str1.length; i++) {
            for (int j = 1; j < str2.length; j++) {
                dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
                if (str1[i] == str2[j]) {
                    dp[i][j] = Math.max(dp[i - 1][j - 1] + 1, dp[i][j]);
                }
            }
        }
        return dp[str1.length - 1][str2.length - 1];
    }
}
